/*
* 部门管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken, recursionGenerateTree} = require("../../config/utils");
// 引入日志
const log = require("../log");

// 获取所有部门列表
router.get("/list", async (req, res) => {
    console.log("===========获取部门列表接口============");
    // 获取参数
    let { deptName, status } = req.query;
    // 拼接sql语句
    let sql = "select * from sys_dept";
    let sql_where = ` where 1=1`;
   
    if(deptName){
        sql_where += ` and dept_name like '%${deptName}%'`;
    }
    if(status){
        sql_where += ` and status = '${status}'`;
    }
    if( deptName || status ){
        sql += sql_where;
    }

    // 查询数据库
    db.query("查询部门列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询部门列表失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
           res.send({code: 200, msg: "查询部门列表成功", data: result });
       }else{
           res.send({code: 200, msg: "查询部门列表成功", data: [], total: 0});
       }
    })
})

// 新增部门
router.post("/", (req, res)=>{
    console.log("===========新增部门接口============");
    // 获取参数
    let {parentId, deptName, orderNum, status, leader, phone, email} = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断部门名称是否重复
    db.query("查询部门名称是否重复", `select * from sys_dept where dept_name = '${deptName}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询部门名称是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "部门名称已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into sys_dept (dept_name, parent_id, order_num, status, leader, phone, email, create_by, create_time)
        values 
        ('${deptName}', '${parentId}','${orderNum}', '${status}', ${leader ? "'"+leader+"'" : null}, 
        ${phone ? "'"+phone+"'" : null}, ${email ? "'"+email+"'" : null},
        '${username}', '${createTime}')`;
        db.query("新增部门", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增部门失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增部门成功"});
            }else{
                res.send({code: 500, msg: "新增部门失败"});
            }
        })
    })
})

// 查询单个部门
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个部门接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个部门", `select * from sys_dept where dept_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个部门失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个部门成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个部门失败"});
        }
    })
})

// 查询已启用的部门列表
router.get("/list/exclude/:id", (req, res) => {
    console.log("===========查询单启用的部门列表接口============");
    // 获取参数
    const id = req.params.id;
   
    db.query("查询启用的部门列表", `select * from sys_dept where status = '0'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询启用的部门列表失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询启用的部门列表成功", data: result});
        }else{
            res.send({code: 500, msg: "查询启用的部门列表失败"});
        }
    })
})

// 修改部门
router.put("/", (req, res)=>{
    console.log("===========修改部门接口============");
    // 获取参数
    let {parentId, deptName, orderNum, status, leader, phone, email, deptId} = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断部门名称是否重复
    db.query("查询部门名称是否重复", `select * from sys_dept where dept_name = '${deptName}' and dept_id != ${deptId}`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询部门名称是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "部门名称已存在"});
            return;
        }
        // 修改数据库
        let sql = `update sys_dept set parent_id = '${parentId}',  dept_name = '${deptName}', order_num = '${orderNum}', status = '${status}',
        leader = ${leader ? "'"+leader+"'" : null}, phone = ${phone ? "'"+phone+"'" : null},  email = ${email ? "'"+email+"'" : null}, 
        update_by = '${username}', update_time = '${updateTime}'
        where dept_id = ${deptId}`;
        db.query("修改部门", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改部门失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改部门成功"});
            }else{
                res.send({code: 500, msg: "修改部门失败"});
            }
        })
    })
})

// 删除部门
router.delete("/:id", (req, res) => {
    console.log("===========删除部门接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from sys_dept where dept_id in(${id})`;
    // 查询数据库
    db.query("删除部门", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除部门失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除部门成功"})
        }else{
            res.send({code: 500, msg: "删除部门失败"})
        }
    })
})

// 查询部门下拉树结构接口
router.get('/treeselect', (req, res) => {
    console.log("===========查询部门下拉树结构接口============");
    // 查询数据库
    db.query("查询部门下拉树结构接口", `select dept_id as id, dept_name as label, parent_id as pid  from sys_dept`, (err, result) => {
        if (err) { 
            res.send({code: 500, msg: '查询部门下拉树结构接口失败'}) 
            return
        }
        if(result.length > 0) {
            // 生成树结构递归
            result = recursionGenerateTree(0, result)
        }
        res.send({
            code: 200,
            msg: '测试数据',
            data: result,
        })
    })
   
})

// 查询角色下对应部门下拉树结构接口
router.get('/roleDeptTreeselect/:id', (req, res) => {
    console.log("===========查询部门下拉树结构接口============");
    // 获取参数
    let {id} = req.params;
    // 连表查询 根据角色id查询部门id，再查询部门信息
    let sql_union = `select dept_id as id, dept_name as label, parent_id as pid  from sys_dept 
    where dept_id in (select dept_id from sys_role_dept where role_id = ${id})`;

    // 查询数据库
    db.query("查询部门下拉树结构接口", sql_union, (err, result) => {
        if (err) { 
            res.send({code: 500, msg: '查询部门下拉树结构接口失败'}) 
            return
        }
        if(result.length > 0) {
            // 生成树结构递归
            result = recursionGenerateTree(0, result)
        }
        res.send({
            code: 200,
            msg: '角色下对应部门下拉树结构成功',
            depts: result,
        })
    })
   
})


module.exports = router;
